package cn.calm.swing.osgi.host;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;

import cn.calm.swing.osgi.host.tracker.MenuServiceTracker;
import cn.calm.swing.osgi.host.tracker.ProjectServiceTracker;
import cn.calm.swing.osgi.host.ui.MainFrame;
import cn.calm.swing.osgi.util.SwingHelper;

public class Activator implements BundleActivator {
	private MainFrame frame;
	private MenuServiceTracker menuServiceTracker;
	private ProjectServiceTracker projectServiceTracker;
	public static final String CONFIG_FILE = "/config.properties";

	@Override
	public void start(final BundleContext context) {
		frame = new MainFrame(context);
		frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		frame.addWindowListener(new WindowAdapter() {

			@Override
			public void windowClosing(WindowEvent evt) {
				try {
					context.getBundle(0).stop();
					System.exit(0);
				} catch (BundleException ex) {
					ex.printStackTrace();
				}
			}
		});
		SwingHelper.center(frame);
		frame.setVisible(true);

		menuServiceTracker = new MenuServiceTracker(context, frame);
		menuServiceTracker.open();
		projectServiceTracker=new ProjectServiceTracker(context, frame);
		projectServiceTracker.open();
	}

	@Override
	public void stop(BundleContext context) throws Exception {
		Runnable runner = new Runnable() {

			@Override
			public void run() {
				menuServiceTracker.close();
				projectServiceTracker.close();
				frame.setVisible(false);
				frame.dispose();
			}
		};

		SwingHelper.swingInvoke(runner);
	}

}
